import React,{useSyncExternalStore} from 'react'

// 自己实现一个简易redux

const store={

  listens:[],
  state:{
    count:3
  },

  reducer(state,action){
    switch(action.type){
      case "ADD":return {
        ...state,
        count:state.count+action.payload
      }
      case "SUB":return {
        ...state,
        count:state.count-action.payload
      }
      default:return state
    }
  },

  subscribe(cb){
    store.listens.push(cb);
  },

  getState(){
    return store.state;
  },

  dispatch(action){
    
    store.state =  store.reducer(store.state,action);

    // 如果新旧状态有变化，那么就发布。
    store.listens.forEach(item=>{
      item();
    })

  }

}

export default function Index() {

  const state = useSyncExternalStore(store.subscribe,()=>store.getState());

  function addCount(){
    store.dispatch({
      type:"ADD",
      payload:5
    })
  }

  return (
    <div>
      <h1>useSyncExternalStore</h1>
      <p>state.count:{state.count}</p>
      <input type="button" value="修改count" onClick={addCount} />
    </div>
  )
}
